package com.prik.command.remotecontrol;

import com.prik.command.Command;
import com.prik.command.commands.*;

/**
 * 有7组开关的遥控器
 **/
public class RemoteControl {


    private static final int BUTTON_SIZE = 7;

    /**
     * 用数组记录遥控器上多个开关对应的命令
     */
    Command[] onCommands;
    Command[] offCommands;

    /**
     * 上一个命令
     */
    Command lastCommand;

    /**
     * 构造方法中初始化数组
     */
    public RemoteControl() {

        onCommands = new Command[BUTTON_SIZE];
        offCommands = new Command[BUTTON_SIZE];

        // 空对象
        Command noCommand = new NoCommand();

        for (int i = 0; i < BUTTON_SIZE; i++) {
            onCommands[i] = noCommand;
            offCommands[i] = noCommand;
        }
        lastCommand = noCommand;
    }

    /**
     * 往遥控器开关上设置命令
     * @param slot
     * @param onCommand
     * @param offCommand
     */
    public void setCommand(int slot, Command onCommand, Command offCommand) {
        onCommands[slot] = onCommand;
        offCommands[slot] = offCommand;
    }

    /**
     * 开
     * @param slot
     */
    public void pushOnButton(int slot) {
        onCommands[slot].execute();
        lastCommand = onCommands[slot];
    }

    /**
     * 关
     * @param slot
     */
    public void pushOffButton(int slot) {
        offCommands[slot].execute();
        lastCommand = offCommands[slot];
    }

    /**
     * 撤销
     */
    public void pushUndoButton() {
        lastCommand.undo();
    }

    /**
     * 重写toString方法，给出遥控器说明书
     * @return
     */
    @Override
    public String toString() {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("\n-------- Remote Control --------\n");
        for (int i = 0; i < BUTTON_SIZE; i++) {
            stringBuffer.append("[slot " + i + "] " + onCommands[i].getClass().getName() + " / " + offCommands[i].getClass().getName() + "\n");
        }
        return stringBuffer.toString();
    }
}